﻿function DBManager() {
    this.db = null;
    //Открытие базы
    this.dbOpen = function (name) {
        if (window.openDatabase) {
            if (!(this.db = openDatabase(name, '1.0', 'mKook Database: ' + name, 4 * 1024 * 1024))) {
                alert("Browser can't create DB");
            }
        } else {
            alert("Browser hasn't WebSQL");
        }
    }
    //Создание таблицы
    this.tbCreate = function (name, arrTable) {
        var query = 'CREATE TABLE IF NOT EXISTS ' + name + '( ';
        var n = arrTable.length - 1;
        for (var i = 0; i < n; i++) {
            query += arrTable[i].col + ' ' + arrTable[i].type + ', ';
        }
        query += arrTable[i].col + ' ' + arrTable[i].type + ' )';
        this.executeQuery(query, [],
            function (t, result) {
                console.log('table ' + name + ' has created');
            },
            function (t, error) {
                console.log('can\'create ' + name + '. ERROR: ' + error);
            }
        );

    }
    //Выбрать из таблицы
    this.tbSelect = function (table, arrSelectQuery, fn_finded, fn_not_finded, fn_error) {
        var query = 'SELECT * FROM ' + table;
        if (arrSelectQuery != null && arrSelectQuery.length > 0) {
            query += ' WHERE ' + arrSelectQuery[0].col + ' = \'' + arrSelectQuery[0].val+'\'';
            for (var i = 1; i < arrSelectQuery.length; i++) {
                query += ' AND ' + arrSelectQuery[i].col + ' = \'' + arrSelectQuery[i].val+'\'';
            }
        }
        this.executeQuery(query, [],
            function (t, result) {
                if (result.rows.length > 0) {
                    fn_finded(result); 
                }
                else {
                    fn_not_finded(result);
                }
            },
            function (t, error) {
                fn_error(error);
            }
        );
    }
    //Вставить в таблицу
    this.tbInsert = function (table, arrInsertQuery, fn_success, fn_error) {
        query = 'INSERT INTO ' + table + ' (';
        var n = arrInsertQuery.length;
        var arr = new Array();
        //Имена столбцов
        for (var i = 0; i < n - 1; i++) {
            query += (arrInsertQuery[i].col+', ');
            arr.push(arrInsertQuery[i].col);
        }
        //Значения
        query += arrInsertQuery[n - 1].col+') VALUES ( ';
        arr.push(arrInsertQuery[n - 1].col);
        for (var i = 0; i < n - 1; i++) {
            query += (arrInsertQuery[i].val+', ')
            arr.push(arrInsertQuery[i].val);
        }
        query += (arrInsertQuery[n - 1].val+')');
        arr.push(arrInsertQuery[n - 1].val);
        //Выполнить запрос
        this.executeQuery(query, [],
        function (t, result) {
            fn_success(result);
        },
        function (t, error) {
            fn_error(error);
        });
    }
    //Обновить значение в таблице
    this.tbUpdate = function (table, arrWhere, arrSet, fn_success, fn_error) {
        var query = 'UPDATE ' + table;
        query += ' SET ' + arrSet[0].col + ' = ' + arrSet[0].val;
        if (arrWhere != null && arrWhere.length > 0) {
            query += ' WHERE ' + arrWhere[0].col + ' = ' + arrWhere[0].val;
            for (var i = 1; i < arrWhere.length; i++) {
                query += ' AND ' + arrWhere[i].col + ' = ' + arrWhere[i].val;
            }
        }
        this.executeQuery(query, [], fn_success, fn_error);
    }
    //Удалить запись из таблицы
    this.tbDelete = function (table, key, value) {
        stringQuery = "DELETE FROM " + table + " WHERE " + key + " = " + value;
        this.executeQuery(stringQuery);
    };
    //Выбрать всю таблицу
    this.tbSelectAll = function (table, fn) {
        stringQuery = "SELECT * FROM " + table;
        this.executeQuery(stringQuery, [], fn);
    };
    //Удалить таблицу
    this.tbDrop = function (table) {
        stringQuery = "DROP TABLE " + table;
        this.executeQuery(stringQuery);
    };
    //Выполнить запрос
    this.executeQuery = function (query, arr, fn_success, fn_error) {
        this.db.transaction(function (t) {
            t.executeSql(query, arr, fn_success, fn_error);
        });
    };
}